#!/bin/sh

# https://github.com/moby/moby/blob/master/contrib/mkimage-alpine.sh
# apline linux build script from docker

set -e

[ $(id -u) -eq 0 ] || {
    printf >&2 '%s requires root\n' "$0"
    exit 1
}

usage() {
    echo 'usage: %s [-r release] [-m mirror] [-a arch]'
    exit 1
}

tmp() {
    ROOTFS=$(mktemp -d ${TMPDIR:-/var/tmp}/alpine-tinyc-XXXXXXXXXX)
    trap "rm -fr $ROOTFS" EXIT TERM INT
}

apkv() {
    curl -sSL $MAINREPO/$ARCH/APKINDEX.tar.gz | tar -Oxz \
        | grep --text '^P:apk-tools-static$' -A1 | tail -n1 | cut -d: -f2
}

getapk() {
    curl -sSL $MAINREPO/$ARCH/apk-tools-static-$(apkv).apk \
        | tar -xz -C $ROOTFS sbin/apk.static
}

mkbase() {
    $ROOTFS/sbin/apk.static --repository $MAINREPO --no-cache --allow-untrusted \
        --root $ROOTFS --initdb add alpine-base
}

conf() {
    printf '%s\n' $MAINREPO > $ROOTFS/etc/apk/repositories
}

clean() {
    rm -f $ROOTFS/sbin/apk.static
}

pack() {
    tar -C $ROOTFS -czf alpine-$REL.$ARCH.tar.gz .
}

REL=${REL:-edge}
MIRROR=${MIRROR:-http://mirrors.ustc.edu.cn/alpine}
MAINREPO=$MIRROR/$REL/main
ARCH=${ARCH:-$(uname -m)}

while getopts "hr:m:a:" opt; do
    case $opt in
    r)
        REL=$OPTARG
        ;;
    m)
        MIRROR=$OPTARG
        ;;
    a)
        ARCH=$OPTARG
        ;;
    *)
        usage
        ;;
    esac
done

tmp
getapk
mkbase
conf
clean
pack